from socket import *
import asyncio , time

async def port_socket(IP,SERVER_PORT):
    dataSocket = socket(AF_INET, SOCK_STREAM)  # 实例化一个socket对象，并指明ip和tcp协议
    # print(loop_num)
    try:
        dataSocket.settimeout(3)
        dataSocket.connect((IP, SERVER_PORT))  # 调用对象，传入ip和server_port
        # print(f'{IP}地址 —— {SERVER_PORT}端口开启')
        success_result.append([IP,SERVER_PORT,'开启'])
        action = '开启'
        dataSocket.close()
    except Exception as e:
        # print(IP,SERVER_PORT,e)
        if str(e) == 'timed out':
            fail_result.append([IP,SERVER_PORT,'未开启'])
        else:
            fail_result.append([IP,SERVER_PORT,str(e)])

async def socket_main(ALL_INFO):
    global success_result , fail_result
    # print("端口检测开始")
    # IP_POOL = ['192.168.0.10','192.168.0.11','192.168.0.200']
    IP_POOL = ALL_INFO[0]
    SERVER_PORT_POOL = ALL_INFO[-1] #22SSH,23Telnet
    # SERVER_PORT_POOL = [22,23] #22SSH,23Telnet
    socket_task_list = []
    success_result = []
    fail_result = []

    for IP in IP_POOL:
        for SERVER_PORT in SERVER_PORT_POOL:
            try:
                SERVER_PORT = int(SERVER_PORT)
            except Exception as e:
                return e
            socket_task_list.append(asyncio.create_task(port_socket(IP,SERVER_PORT),name=f'{IP} {SERVER_PORT}_task'))

    # print("主协程开启")
    done,pending = await asyncio.wait(socket_task_list, timeout=30) #完成的协程返回值写入到done中，未完成则写到pending中。
    # print('主协程结束')
    return success_result+fail_result

if __name__ == '__main__':
    ALL_INFO = [['192.168.0.10','192.168.0.11','192.168.0.200'],['22','23']]
    result = asyncio.run(socket_main(ALL_INFO))
    print(result)